using System.Collections.Immutable;
using DimensionsHelper.LanguageService.Symbols;
using DimensionsHelper.LanguageService.Syntax;

namespace DimensionsHelper.LanguageService;

public class AnalysisIdentifier : AnalysisExpression
{

    internal AnalysisIdentifier(Identifier syntaxNode, AnalysisNode? parent) : base(AnalysisBoundKinds.LocalId,
        syntaxNode, parent)
    {
        Syntax = syntaxNode;
    }

    public override Identifier Syntax { get; }


    public override IEnumerable<AnalysisNode> GetChildren()
    {
        return ImmutableArray<AnalysisNode>.Empty;
    }

    internal override void AddChild(AnalysisNode child)
    {
        throw new NotSupportedException("AnalysisIdentifier cannot have children.");
    }

    public override AnalysisExpression? WithImplicitlyConversion(ValueTypeSymbol targetType)
    {
        // 只有在绑定了类型符号以后，此方法才能起作用。表达式的类型绑定应当在Binder中进行。
        ISymbol symbol = GetSymbol();
        // 当符号是 Undefined 时，表示表达式符号尚未绑定。
        if (symbol.IsUndefined)
        {
            return null;
        }
        // 标识符的绑定符号可能不是值类型，在此处需要推导最终类型
        ITypeSymbol typeSymbol = ((ITypeSymbol)symbol).GetFinalBindableBindingOrThis();
        return targetType.IsAssignableFrom(typeSymbol) ? this : null;
    }
}

public static partial class AnalysisNodeFactory
{
    /// <summary>
    /// 创建一个标识符
    /// </summary>
    /// <param name="syntaxNode">原始的语法节点</param>
    /// <param name="parent">父节点，可以忽略</param>
    /// <param name="withSymbol">此节点所处的With语句上下文类型符号</param>
    public static AnalysisIdentifier Identifier(Identifier syntaxNode, AnalysisNode? parent, ITypeSymbol? withSymbol)
    {
        return new AnalysisIdentifier(syntaxNode, parent).WithContainingWithSymbol(withSymbol);
    }
}